package home.contaduria.web;

import java.util.Collection;

import home.contaduria.domain.Client;
import home.contaduria.domain.Income;
import home.contaduria.domain.IncomeType;
import home.contaduria.service.IncomeService;
import home.contaduria.service.IncomeTypeService;
import home.contaduria.support.util.WebUtil;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@RequestMapping("/incomes")
@Controller
public class IncomeController {
    private IncomeService incomeService;
    private IncomeTypeService incomeTypeService;

    @Autowired
    public IncomeController(IncomeService incomeService, IncomeTypeService incomeTypeService) {
        this.incomeService = incomeService;
        this.incomeTypeService = incomeTypeService;
    }

    @RequestMapping(method = RequestMethod.POST)
    public String create(@Valid Income income, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            uiModel.addAttribute("income", income);
            WebUtil.addDateTimeFormatPatterns(uiModel, "income_operationdate_date_format");
            return "incomes/create";
        }
        uiModel.asMap().clear();

        Client client = (Client) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        income.setClient(client);
        incomeService.createIncome(income);

        return "redirect:/incomes/" + WebUtil.encodeUrlPathSegment(income.getId().toString(), httpServletRequest);
    }
    
    @RequestMapping(params = "form", method = RequestMethod.GET)
    public String createForm(Model uiModel) {
        uiModel.addAttribute("income", new Income());
        WebUtil.addDateTimeFormatPatterns(uiModel, "income_operationdate_date_format");
        return "incomes/create";
    }
    
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String show(@PathVariable("id") Long id, Model uiModel) {
        WebUtil.addDateTimeFormatPatterns(uiModel, "income_operationdate_date_format");
        uiModel.addAttribute("income", incomeService.readIncome(id));
        uiModel.addAttribute("itemId", id);
        return "incomes/show";
    }
    
    @RequestMapping(method = RequestMethod.GET)
    public String list(@RequestParam(value = "page", required = false) Integer page,
            @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        Client client = (Client) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (page != null || size != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            uiModel.addAttribute("incomes", incomeService.listIncomes(client, page == null ? 0 : (page.intValue() - 1) * sizeNo, sizeNo));
            float nrOfPages = (float) incomeService.countIncomesNumber(client) / sizeNo;
            uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        } else {
            uiModel.addAttribute("incomes", incomeService.listIncomes(client));
        }
        WebUtil.addDateTimeFormatPatterns(uiModel, "income_operationdate_date_format");
        return "incomes/list";
    }
    
    @RequestMapping(method = RequestMethod.PUT)
    public String update(@Valid Income income, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            uiModel.addAttribute("income", income);
            WebUtil.addDateTimeFormatPatterns(uiModel, "income_operationdate_date_format");
            return "incomes/update";
        }
        uiModel.asMap().clear();
        Client client = (Client) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        income.setClient(client);
        incomeService.updateIncome(income);
        return "redirect:/incomes/" + WebUtil.encodeUrlPathSegment(income.getId().toString(), httpServletRequest);
    }
    
    @RequestMapping(value = "/{id}", params = "form", method = RequestMethod.GET)
    public String updateForm(@PathVariable("id") Long id, Model uiModel) {
        uiModel.addAttribute("income", incomeService.readIncome(id));
        WebUtil.addDateTimeFormatPatterns(uiModel, "income_operationdate_date_format");
        return "incomes/update";
    }
    
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public String delete(@PathVariable("id") Long id, @RequestParam(value = "page", required = false) Integer page,
            @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        incomeService.deleteIncome(id);
        uiModel.asMap().clear();
        uiModel.addAttribute("page", (page == null) ? "1" : page.toString());
        uiModel.addAttribute("size", (size == null) ? "10" : size.toString());
        return "redirect:/incomes";
    }
    
    @ModelAttribute("incomeTypes")
    public Collection<IncomeType> populateIncomeTypes(){
        Client client = (Client) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return incomeTypeService.loadClientIncomeTypes(client);
    }

    // @ModelAttribute("incomes")
    // public Collection<Income> populateIncomes() {
    // return Income.findAllIncomes();
    // }
    
    // void addDateTimeFormatPatterns(Model uiModel) {
    // uiModel.addAttribute("income_operationdate_date_format",
    // DateTimeFormat.patternForStyle("S-", LocaleContextHolder.getLocale()));
    // }
    //
    // String encodeUrlPathSegment(String pathSegment, HttpServletRequest
    // httpServletRequest) {
    // String enc = httpServletRequest.getCharacterEncoding();
    // if (enc == null) {
    // enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
    // }
    // try {
    // pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
    // }
    // catch (UnsupportedEncodingException uee) {}
    // return pathSegment;
    // }
}
